package com.finger.wx.assistant.util.xml;

import android.annotation.SuppressLint;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;


public class Node implements Serializable {
	// 可以对Node对象持久化保存
	private static final long serialVersionUID = 1L;
	private int id;
	// 节点类型
	private String title;
	// 节点内容
	private String text;
	// 节点属性集合
	private Map<String, String> attributes = new HashMap<String, String>();
	// 子节点集合
	private List<Node> childNodes = new LinkedList<Node>();

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public Map<String, String> getAttribute() {
		return attributes;
	}

	public void setAttribute(Map<String, String> attribute) {
		this.attributes = attribute;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

	public List<Node> getChildNode() {
		return childNodes;
	}

	public void setChildNode(List<Node> childNode) {
		this.childNodes = childNode;
	}

	// 将属性集合转换成一条完整的字符串
	private String attrToString() {
		if (attributes.isEmpty()) {
			return "";
		}
		Iterator<Entry<String, String>> its = attributes.entrySet().iterator();
		StringBuffer buff = new StringBuffer();
		while (its.hasNext()) {
			Entry<String, String> entry = its.next();
			buff.append(entry.getKey() + "=\"" + entry.getValue() + "\" ");
		}
		return " " + buff.toString().trim();
	}

	// 输出完整的节点字符串也用到了递归
	@SuppressLint("NewApi")
	@Override
	public String toString() {
		String attr = attrToString();
		if (childNodes.isEmpty() && text == null) {
			return "<" + title + attr + "/>\n";
		} else if (childNodes.isEmpty() && text != null) {
			return "<" + title + attr + ">\n" + text + "\n" + "</" + title + ">\n";
		} else {
			StringBuffer buff = new StringBuffer();
			buff.append("<" + title + attr + ">\n");
			if (!text.isEmpty()) {
				buff.append(text + "\n");
			}
			for (Node n : childNodes) {
				buff.append(n.toString());
			}
			buff.append("</" + title + ">\n");
			return buff.toString();
		}
	}

	public boolean isHaveChildren() {
		return childNodes.size() > 0 ? true : false;
	}

}